package ch.upndown.upndown.utils;

import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import ch.upndown.upndown.OverviewFragment;
import ch.upndown.upndown.R;
import ch.upndown.upndown.database.DatabaseAccess;
import ch.upndown.upndown.model.Website;

/**
 * Created by DonMiguel on 08.08.2014.
 */
public class UrlValidater implements View.OnClickListener {
    private final Dialog dialog;
    private final DatabaseAccess myDb;
    private final OverviewFragment overviewFragment;
    private final Context context;

    public UrlValidater(Dialog dialog, Context context, OverviewFragment overviewFragment){
        this.dialog = dialog;
        this.myDb = DatabaseAccess.getInstance(context);
        this.overviewFragment = overviewFragment;
        this.context = context;
    }

    @Override
    public void  onClick(View view){
        Website website = new Website();
        EditText name = (EditText) dialog.findViewById(R.id.dialog_add_website_name);
        if (name.getText().toString() == null){
            website.setTitle("No-Name Website");
        }else{
            website.setTitle(name.getText().toString());
        }
        EditText url = (EditText) dialog.findViewById(R.id.dialog_add_website_url);

        String[] schemes = {"http","https"}; // ftp wäri ou no möglech, chamesech ja überlege...
        org.apache.commons.validator.routines.UrlValidator urlValidator = new org.apache.commons.validator.routines.UrlValidator(schemes);
        if (urlValidator.isValid(url.getText().toString())) {
            website.setUrl(url.getText().toString());
            myDb.addWebsite(website);
            overviewFragment.loadWebsites();
            dialog.dismiss();
        }else{
            Toast toast = Toast.makeText(context, context.getResources().getString(R.string.site_invalid), Toast.LENGTH_SHORT);
            toast.show();
        }
    }
}
